<?php 
namespace xfyzf\user\controller;
use lib\Commontc;
use lib\PluginScanner;
use lib\XFDB;
class User{
    //登录
    public function login(){
        global $conf,$islogin_user;
        if(isset(input("get")['logout'])){
            $expireTime = time() - 99999999999;
            setcookie("user_token", "", $expireTime);
            @header('Content-Type: text/html; charset=UTF-8');
             Commontc::truetc("注销成功！",rethreffun('./login'));
        }
        if($islogin_user == 1)Commontc::truetc("您已登录！",rethreffun('./index'));
        if (!empty(input("get")['trade_no']) && input("get")['trade_status'] == 'TRADE_SUCCESS') {
            Commontc::truetc("恭喜您 注册成功！",rethreffun('./login'));
        }
        $mod = 'login';
        $loadfile = \lib\LoginTemplate::load($mod);
        
        
        include $loadfile;
    }
    public function Reg(){
        global $conf,$islogin_user;
        if($islogin_user == 1)Commontc::truetc("您已登录！",rethreffun('./index'));
        if ($conf['reg_open']!= 1)Commontc::falsetc("管理员未开放注册！",rethreffun('./login'));
        $name1="请输入邮箱验证码";
        $mod = 'reg';
        $loadfile = \lib\LoginTemplate::load($mod);
        include $loadfile;
    }
    
    
    public function index(){
        global $islogin_user,$user_pid,$conf,$userrow;
        $title='用户中心';
        if($islogin_user!=1 && empty($user_pid))Commontc::falsetc("请先登录",rethreffun('./login'));
        $pluginDir = ROOT_CLASS . '/xfyzf/plugins';
        $pluginInfos = PluginScanner::getPluginInfo($pluginDir);
        $qrlistmenuhtml = '';
        
        foreach ($pluginInfos as $menu){
            if (isset($menu['menu'])){
                $head = $menu['menu'];
                if (!empty($head['name']) && !empty($head['url']) && $head['menu'] == 'Qrlist'){
                    $qrlistmenuhtml.=' <li> <a class="multitabs" data-url="./'.htmlspecialchars($head['url']).'" href="javascript:void(0)">'.htmlspecialchars($head['name']).'</a> </li>';
                }
            }
            
        }
        include usertem.'index.php';
    }
    
    public function index_min(){
         global $conf,$islogin_user,$user_pid,$userrow,$date;
         $title= '用户中心';
         
         include usertem.'assets.php';
         if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
         if($userrow['emailauth']!=1)email_authti();
         $vip = ($userrow['alipay_free_vip_time'] > $date || $userrow['qqpay_free_vip_time'] > $date || $userrow['wxpay_free_vip_time'] > $date) ? '免挂会员' : '非会员';
         $sql = "SELECT COUNT(*) as count FROM pay_order WHERE `pid`='{$userrow['pid']}'"; 
         $count1 = executeSQLQuery($sql)['count'];
         $sql = "SELECT COUNT(*) as count FROM pay_order WHERE `pid`='{$userrow['pid']}' AND `status` = '1'"; 
         $count2 = executeSQLQuery($sql)['count'];
         $sql="SELECT sum(money) as count from pay_order WHERE status='1' AND `pid`='{$userrow['pid']}'";
         $count3 = executeSQLQuery($sql)['count'];
         $order = [];
         $paymentTypes = ['wxpay', 'alipay', 'qqpay', 'usdtpay','all'];
         // 构造当天开始时间（即0点）
         $today = date("Y-m-d");
         $lastday = date("Y-m-d", strtotime("-1 day"));
         $startTime = $today . " 00:00:00";
         $endTime = $today . " 23:59:59";
          // 昨天的开始时间
        $startTimeYesterday = $lastday . " 00:00:00";
        // 昨天的结束时间
        $endTimeYesterday = $lastday . " 23:59:59";
         foreach ($paymentTypes as $type){
            $sql1 = '';
            if($type!='all')$sql1 = "AND `type`='$type'";
             $sql = "SELECT count(*) as count FROM pay_order WHERE addtime >= '$startTime' AND addtime <= '$endTime' $sql1 AND `status` ='1' AND `pid`='{$userrow['pid']}'";
             $order[$type]['todayOrder'] = executeSQLQuery($sql)['count']??'0';
            $sql = "SELECT SUM(money) as count FROM pay_order WHERE addtime >= '$startTime' AND addtime <= '$endTime' $sql1 AND status ='1' AND `pid`='{$userrow['pid']}'";
            $order[$type]['todayOrdermoney'] = executeSQLQuery($sql)['count']??'0.00';
            
            $sql = "SELECT count(*) as count FROM pay_order WHERE addtime >= '$startTimeYesterday' AND addtime <= '$endTimeYesterday' $sql1 AND status ='1' AND `pid`='{$userrow['pid']}'";
            $order[$type]['lastday'] = executeSQLQuery($sql)['count']??'0';
            
            $sql = "SELECT SUM(money) as count FROM pay_order WHERE addtime >= '$startTimeYesterday' AND addtime <= '$endTimeYesterday' $sql1 AND status ='1' AND `pid`='{$userrow['pid']}'";
            $order[$type]['lastdaymoney'] = executeSQLQuery($sql)['count']??'0.00';
            
            $todayOrder = $order[$type]['todayOrder'];
            $lastDayOrder = $order[$type]['lastday']; 
            if ($lastDayOrder > 0) {
                $growthRate = (($todayOrder - $lastDayOrder) / $lastDayOrder) * 100;
            } else {
                // 如果昨天的订单数量为0，直接设置增长率为今天的订单数量（因为不能除以0）
                // 或者可以设置为无限大，或者根据实际情况处理
                $growthRate = $todayOrder > 0 ? 100 : 0; // 如果今天有订单，且昨天为0，则增长率为100，否则为0
            }
            
            $order[$type]['t'] = sprintf("%.2f", $growthRate);
        }
        
         include usertem.'index_min.php';
         
    }
    public function order(){
        global $conf,$islogin_user,$userrow,$user_pid;
        $title= '订单列表';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
         $get = input("get");
         $my = isset($get['my'])??'';
         if($my == 'search' || !empty($get['value'])){
             $column = $get['column'];
             $value  = $get['value'];
             $sql = "SELECT * FROM pay_order WHERE `$column` = :value AND `pid` = :pid";
             $paramsSelect = [
                'value' => $value,
                'pid' => $user_pid
            ];
            $numrows = safeSqlQuery($sql, $paramsSelect)['count']; 
            $html1 = '<font color=red>'.$value.'</font>';
            $con='包含 '.$html1.' 的共有 <b>'.$numrows.'</b> 条记录';
         }else{
             $sql = "SELECT * FROM pay_order WHERE  `pid` = :pid";
             $paramsSelect = [
                'pid' => $user_pid
            ];
             $numrows = safeSqlQuery($sql, $paramsSelect)['count'];
             $con='共有 <b>'.$numrows.'</b> 条记录';
         }
         $pagesize=20;
         $pages=0;
         if(isset($numrows)){
                $pages=intval($numrows/$pagesize)+1;
         }
         if(isset($get['page'])){
             $page=intval($get['page']);
         }else{
             $page=1;
         }
          $offset = $pagesize * ($page - 1);
          $conditions = [];
          $params = [];
          if (isset($get['my']) && $get['my'] == 'search' && isset($get['column']) && isset($get['value'])){
              $conditions[] = "`{$get['column']}` = :value";
              $params['value'] = $get['value'];
          }
          $conditions[] = "`pid` = :pid";
          $params['pid'] = $user_pid;
          $whereClause = implode(' AND ', $conditions);
          $sql = "SELECT * FROM pay_order WHERE $whereClause ORDER BY addtime DESC LIMIT $offset, $pagesize";
          $result = safeSqlQuery($sql, $params)['result'];
        include usertem.'order.php';
        
    }
    public function Qrlist(){
        global $islogin_user,$userrow,$user_pid,$conf;
        $title= '免挂机码子管理';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        $get = input("get");
        $types = ['alipay', 'wxpay', 'qqpay'];
        $cookie_ok_counts = [];
        $cookie_no_counts = [];
        
        foreach ($types as $type) {
            $sql_cookie_ok = "SELECT COUNT(*) AS count FROM pay_qrlist WHERE status = '1' AND hook_type IN (0, 2) AND type = '{$type}' AND `pid` = '{$user_pid}'";
            $cookie_ok_counts[$type] = executeSQLQuery($sql_cookie_ok)['count'];
        
            $sql_cookie_no = "SELECT COUNT(*) AS count FROM pay_qrlist WHERE status != '1' AND hook_type IN (0, 2) AND type = '{$type}' AND `pid` = '{$user_pid}'";
            $cookie_no_counts[$type] = executeSQLQuery($sql_cookie_no)['count'];
        }
        $sql  = "SELECT COUNT(*) AS count from pay_qrlist WHERE `pid`='{$user_pid}' and hook_type IN (0, 2) and `type`!='usdtpay'";
        
        $numrows = executeSQLQuery($sql)['count'];
        $con='共有 <b>'.$numrows.'</b> 条记录';
         $pagesize=5;
         $pages=0;
         if(isset($numrows)){
                $pages=intval($numrows/$pagesize)+1;
         }
         if(isset($get['page'])){
             $page=intval($get['page']);
         }else{
             $page=1;
         }
         $offset = $pagesize * ($page - 1);
         $conditions[] = "`pid` = :pid";
         $params['pid'] = $user_pid;
         $whereClause = implode(' AND ', $conditions);
         $sql = "SELECT * FROM pay_qrlist WHERE $whereClause AND hook_type IN (0, 2) AND `type`!='usdtpay' ORDER BY id DESC LIMIT $offset, $pagesize";
         $result = safeSqlQuery($sql, $params)['result'];
         $sql = "SELECT * FROM pay_wechat_trumpet WHERE status=1 ORDER BY id ASC";
         $dyrow = safeSqlQuery($sql, []);
        
         $option = '';
         if($dyrow['count']>0){
             $option = '<option value="">请选择店员账号</option>';
             foreach ($dyrow['result'] as $row){
                 $option .= '<option value="'.$row['wx_user'].'">'.$row['wx_name'].'</option>';
             }
         }else{
            $option = '<option value="">暂无店员号</option>';
         }
         
         $macurl = '';
         $uosurl = '';
         $wxyunall = XFDB::wxyunurlall();
         if($wxyunall['count']>0){
             foreach ($wxyunall['result'] as $row){
                 if($row['code'] == '1'){
                     $macurl .='<option value="'.$row['id'].'">'.$row['name'].'</option>';
                 }else{
                     $uosurl .='<option value="'.$row['id'].'">'.$row['name'].'</option>';
                 }
             }
         }
         
         
        $my = input("get")['my']??'list';
        $id = input("get")['id']??'';
        if($my == 'edit' || !empty($id)){
            $sql = "SELECT * FROM  pay_qrlist where id = '$id' limit 1";
            $row = executeSQLQuery($sql);
            $ckstatus = 'CooKie已失效，请勿强制开启二维码."';
            if(strlen($row['cookie'])>2){
                $ckstatus = 'CooKie状态正常';
            }
            if($row['cookie'] == 'xfqymckxy' || $row['cookie'] == 'xfqydmfxy'){
               $app =  generateAlipayInfo($row);
            }
            
        }
        include usertem.'Qrlist.php';
    }
    public function SDK(){
        global $conf;
        if($conf['test_open'] == '0')Commontc::falsetc("管理员 未开启测试付款",rethreffun('./index_min'));
        $title = '测试付款';
        if(!isMobile()){
            
            include usertem.'PCSDK.php';
        }else{
            include usertem.'webSDK.php';
        }
    }
    public function usdt(){
        global $islogin_user,$userrow,$user_pid,$conf;
        $title= 'USDT码子管理';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        $get = input("get");
        $sql  = "SELECT COUNT(*) AS count from pay_qrlist WHERE `pid`='{$user_pid}' and `type`='usdtpay'";
        $numrows = executeSQLQuery($sql)['count'];
        $con='您有 <b>'.$numrows.'</b> 条USDT收款地址';
        $pagesize=5;
         $pages=0;
         if(isset($numrows)){
                $pages=intval($numrows/$pagesize)+1;
         }
         if(isset($get['page'])){
             $page=intval($get['page']);
         }else{
             $page=1;
         }
         $offset = $pagesize * ($page - 1);
         $conditions[] = "`pid` = :pid";
         $params['pid'] = $user_pid;
         $whereClause = implode(' AND ', $conditions);
         $sql = "SELECT * FROM pay_qrlist WHERE $whereClause  AND `type`='usdtpay' ORDER BY id DESC LIMIT $offset, $pagesize";
         $result = safeSqlQuery($sql, $params)['result'];
         $my  = $get['my']??'list';
         $id  = $get['id']??'';
         if(!empty($id) && $my == 'edit'){
             $sql = "SELECT * FROM  pay_qrlist where id = '$id' limit 1";
             $row = executeSQLQuery($sql);
         }
        include usertem.'usdt.php';
    }
    public function PC_Qrlist(){
        global $islogin_user,$userrow,$user_pid,$conf;
        $title= 'PC挂机码子管理';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
         $get = input("get");
         $my  = $get['my']??'list';
         $id  = $get['id']??'';
         $types = ['alipay', 'wxpay', 'qqpay'];
         $cookie_ok_counts = [];
         $cookie_no_counts = [];
        
        foreach ($types as $type) {
            $sql_cookie_ok = "SELECT COUNT(*) AS count FROM pay_qrlist WHERE status = '1' AND hook_type ='1' AND type = '{$type}' AND `pid` = '{$user_pid}'";
            $cookie_ok_counts[$type] = executeSQLQuery($sql_cookie_ok)['count'];
        
            $sql_cookie_no = "SELECT COUNT(*) AS count FROM pay_qrlist WHERE status != '1' AND hook_type ='1' AND type = '{$type}' AND `pid` = '{$user_pid}'";
            $cookie_no_counts[$type] = executeSQLQuery($sql_cookie_no)['count'];
        }
        $sql  = "SELECT COUNT(*) AS count from pay_qrlist WHERE `pid`='{$user_pid}' and hook_type ='1' ";
        $numrows = executeSQLQuery($sql)['count'];
        $con='共有 <b>'.$numrows.'</b> 条记录';
        $sql  = "SELECT COUNT(*) AS count from pay_qrlist WHERE `pid`='{$user_pid}'";
        $numrow = executeSQLQuery($sql)['count'];
        $pagesize=5;
         $pages=0;
         if(isset($numrows)){
                $pages=intval($numrows/$pagesize)+1;
         }
         if(isset($get['page'])){
             $page=intval($get['page']);
         }else{
             $page=1;
         }
         $offset = $pagesize * ($page - 1);
         $conditions[] = "`pid` = :pid";
         $params['pid'] = $user_pid;
         $whereClause = implode(' AND ', $conditions);
         $sql = "SELECT * FROM pay_qrlist WHERE $whereClause AND hook_type ='1' AND `type`!='usdtpay' ORDER BY id DESC LIMIT $offset, $pagesize";
         $result = safeSqlQuery($sql, $params)['result'];
         if(!empty($id) && $my == 'edit'){
             $sql = "SELECT * FROM  pay_qrlist where id = '$id' limit 1";
             $row = executeSQLQuery($sql);
             $ckstatus = 'CooKie已失效，请勿强制开启二维码."';
            if(strlen($row['cookie'])>2){
                $ckstatus = 'CooKie状态正常';
            }
         }
         $token = json_encode(array("pid"=>$userrow['pid'],"key"=>$userrow['key']));
         $token= aes256auth($token,PCTOKENKEY);
         
        include usertem.'PC_Qrlist.php';
    }
    public function Api_Set(){
         global $islogin_user,$userrow,$user_pid,$conf,$httphost;
         $title= '商户设置';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        $url = (!empty($conf['duijie_url']))?$conf['duijie_url']:$httphost;
        
        include usertem.'Api_Set.php';
    }
    public function Pay_Vip(){
        global $islogin_user,$userrow,$conf,$date;
        $title= '商户充值';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
         if (!empty(input("get")['trade_no']) && input("get")['trade_status'] == 'TRADE_SUCCESS') {
             Commontc::truetc("恭喜你，充值成功！",rethreffun('./Pay_Vip'));
        }
        include usertem.'Pay_Vip.php';
    }
    public function Meal(){
        global $islogin_user,$userrow,$conf;
        $title= '额度套餐';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
         if (!empty(input("get")['trade_no']) && input("get")['trade_status'] == 'TRADE_SUCCESS') {
             Commontc::truetc("恭喜你，充值成功！",rethreffun('./Meal'));
        }
        $meals = json_decode($conf['pay_meal'],true);
        if(!is_array($meals)){
            $meals = [];
        }
        $html = '';
        foreach ($meals as $meal){
            if($meal['recharge']>0 && $meal['money']>0){
                $html.='<option value="'.$meal['recharge'].'">支付'.$meal['recharge'].'元得'.$meal['money'].'额度</option>';
            }
        }
        
        include usertem.'Meal.php';
    }
    public function Package(){
        global $islogin_user,$userrow,$conf;
        $title= '额度套餐';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        if (!empty(input("get")['trade_no']) && input("get")['trade_status'] == 'TRADE_SUCCESS') {
            Commontc::truetc("恭喜你，购买成功！",rethreffun('./Package'));
        }
        $sql    = "SELECT * FROM pay_package WHERE `status`='1'";
        $data   = safeSqlQuery($sql, []);
        $result = '';
        if($data['count']>0){
            $result = $data['result']??'';
        }
        include usertem.'Package.php';
    }
    public function Pay_Set(){
        global $islogin_user,$userrow,$conf;
        $title= '支付设置';
        include usertem.'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        include usertem.'Pay_Set.php';
    }
    public function Work(){
        global $islogin_user,$userrow,$conf,$user_pid;
         $title = "发起工单";
         include usertem . 'assets.php';
         if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        
         if($conf['work_zt'] == '0')Commontc::truetc("管理员未开启工单功能！",rethreffun('./index_min'));
         $sql  = "SELECT COUNT(*) AS count from pay_work WHERE `uid`='{$user_pid}'";
         $get  = input("get");
         $inviteCount = executeSQLQuery($sql)['count'];
         $pagesize=10;
         $pages=0;
         if(isset($inviteCount)){
            $pages=intval($inviteCount/$pagesize)+1;
         }
         if(isset($get['page'])){
            $page=intval($get['page']);
         }else{
            $page=1;
         }
        $offset = $pagesize * ($page - 1);
        $sql = "SELECT * FROM pay_work WHERE `uid`=:uid ORDER BY id DESC LIMIT $offset, $pagesize";
        $params=[
                'uid' =>$user_pid
        ];
        $result = safeSqlQuery($sql, $params)['result'];
        
         include usertem . 'Work.php';  
    }
    public function Pay_cs(){
        global $islogin_user,$userrow,$conf,$user_pid;
        $title = "商户支付测试";
        include usertem . 'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        if (!empty(input("get")['trade_no']) && input("get")['trade_status'] == 'TRADE_SUCCESS') {
            Commontc::truetc("恭喜你，支付成功！",rethreffun('./Pay_cs'));
        }
        
        include usertem . 'Pay_cs.php';  
    }
    public function Plugin(){
        global $islogin_user,$userrow,$conf,$user_pid;
        $title = "插件合集下载";
        include usertem . 'assets.php';
        if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
        $sql  = "SELECT COUNT(*) AS count from pay_down";
        $inviteCount = executeSQLQuery($sql)['count'];
        $pagesize=10;
         $pages=0;
         if(isset($inviteCount)){
            $pages=intval($inviteCount/$pagesize)+1;
         }
         if(isset($get['page'])){
            $page=intval($get['page']);
         }else{
            $page=1;
         }
        $offset = $pagesize * ($page - 1);
        $sql = "SELECT * FROM pay_down  ORDER BY id DESC LIMIT $offset, $pagesize";
        $result = safeSqlQuery($sql, [])['result'];
        
        include usertem . 'Plugin.php';  
    }
    public function juhe(){
         global $islogin_user,$userrow,$conf,$user_pid,$httphost;
         $title = "聚合支付";
         include usertem . 'assets.php';
         if($islogin_user!=1)Commontc::falsetc("请先登录",rethreffun('./login'));
         if($conf['juheshoukuan'] == 0)Commontc::truetc("管理员未开启聚合支付功能！",rethreffun('./index_min'));
         $merchant = authcode($user_pid, 'ENCODE', SYS_KEY);
         $code_url = $httphost.'/User/paypage?merchant='.urlencode($merchant);
         $username = $userrow['codename']??$userrow['username'];
         include usertem . 'juhe.php';  
    }
    public function paypage(){
        global $conf;
        $get = input("get");
        $merchant = isset($get['merchant'])?trim($get['merchant']):sysmsg('参数不完整');
        $pid = authcode($merchant, 'DECODE', SYS_KEY);
        $sql = "SELECT * FROM pay_user WHERE pid=:pid limit 1";
        $date = array(
            'pid'=>$pid
            );
        $userrow = safeSqlQuery($sql,$date)['result'][0]??'';
        if(!$userrow)sysmsg('非法操作');
        $codename = $userrow['codename']??$userrow['username'];
        
        include usertem . 'paypage.php';  
    }
    public function Retrieve(){
        global $islogin_user,$conf;
        if($islogin_user==1)Commontc::falsetc("您已登录",rethreffun('./index'));
        if($conf['zh_open'] != '1')Commontc::falsetc("管理员未开启找回功能",rethreffun('./login'));
        $xf_zzurl=get_curl('https://auth.daoh.top/api/yiye.php');
        $mod = 'Retrieve';
        $loadfile = \lib\LoginTemplate::load($mod);
        include $loadfile;
    }
}



?>